﻿using LeSoft.Application.Bussiness;
using LeSoft.Application.Cache;
using LeSoft.Application.Entity;
using LeSoft.Application.Code;
using LeSoft.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LeSoft.Application.Web.Areas.ResourceManage.Controllers
{
    public class RS_PStructUserController : MvcControllerBase
    {
        private PStructCache pstructCache = new PStructCache();
        private OrganizeCache organizeCache = new OrganizeCache();
        private PStructBLL pstructBLL = new PStructBLL();
        private RoomBLL rbll = new RoomBLL();
        private CustomerInfoBLL customerInfoBLL = new CustomerInfoBLL();
        private RelationPCBLL relationPCBLL = new RelationPCBLL();
        private LiveInBillBLL livebll = new LiveInBillBLL();
        #region 视图

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult LiveIndex()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult LiveBillForm()
        {
            return View();
        }
        public ActionResult AddForm()
        {
            ViewBag.Mode = new CodeRuleBLL().CheckBillCodeMode(((int)CodeRuleEnum.LiveInBill).ToString());
            return View();
        }

        public ActionResult AddPStructForm()
        {
            return View();
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <returns></returns>

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Form()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Details()
        {
            return View();
        }
        [HttpGet]
        public ActionResult RoomDetail()
        {
            return View();
        }
        [HttpGet]
        public ActionResult RoomMeter()
        {
            return View();
        }
        #endregion

        #region 查询数据
        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="pagination">分页</param>
        /// <param name="pstructId"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetListJson(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            if (!string.IsNullOrEmpty(queryJson))
            {
                var queryParam = queryJson.ToJObject();
                if (!queryParam["OrganizeId"].IsEmpty())
                {
                    string OrganizeId = organizeCache.GetSonOrganizeId(queryParam["OrganizeId"].ToString());
                    queryParam["OrganizeId"] = OrganizeId;
                }
                queryJson = queryParam.ToJson();
            }
            var data = customerInfoBLL.GetPageList(pagination, queryJson);
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns>返回列表Json</returns>
        [HttpGet]
        public ActionResult GetFormJson(string keyValue)
        {
            var psdata = customerInfoBLL.GetEntity(keyValue);
            var PStructId = relationPCBLL.GetEntity(keyValue, "CustomerId") != null ? relationPCBLL.GetEntity(keyValue, "CustomerId").PStructId : "";
            var model = relationPCBLL.GetCustomerIdByEntity(keyValue);
            var obj = new { data = psdata, model = model, PStructId = PStructId };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 查询房间用户信息
        /// </summary>
        /// <param name="OrganizeId"></param>
        /// <param name="PStructId"></param>
        /// <returns></returns>
        public ActionResult GetCustomerInfo(string RelationPCId)
        {
            var relationPC = relationPCBLL.GetEntity(RelationPCId);
            if (relationPC != null)
            {
                var roomInfo = pstructBLL.GetRoomEntity(relationPC.PStructId);
                var customerinfo = customerInfoBLL.GetEntity(relationPC.CustomerId);
                var data = new
                {
                    Type = relationPC.CustomerType,
                    Area = roomInfo != null ? roomInfo.RoomInfo.Area : 0,
                    Name = customerinfo.Name,
                    Code = customerinfo.Code,
                    LinkMan = customerinfo.LinkMan,
                    LinkManPhone = customerinfo.LinkPhoneNum
                };
                return Content(data.ToJson());
            }
            else
            {
                return null;
            }
        }



        #endregion
        #region 验证数据
        /// <summary>
        /// 检验房间是否有其他人
        /// </summary>
        /// <param name="PStructID"></param>
        /// <param name="keyValue"></param>
        /// <returns>true-表示没有</returns>
        [HttpGet]
        public ActionResult ExistEnabledCustomer(string PStructID, string keyValue, string CustomerType)
        {
            bool IsOk = new RelationPCBLL().ExistEnabledCustomer(PStructID, keyValue, CustomerType);
            return Content(IsOk.ToString());
        }
        #endregion
        #region 提交数据
        /// <summary>
        /// 删除机构
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult RemoveForm(string keyValue)
        {
            customerInfoBLL.RemoveForm(keyValue);
            return Success("删除成功。");
        }
        /// <summary>
        /// 保存业户资料表单（新增、修改）
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="PStructId">房产ID</param>
        /// <param name="pstructUserEntity">房产与用户关系实体</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveForm(string keyValue, RelationPCEntity relationPCEntity, CustomerInfoEntity customerInfoEntity)
        {
            bool IsOk = new RelationPCBLL().ExistEnabledCustomer(relationPCEntity.PStructId, keyValue, customerInfoEntity.Type);
            if (IsOk)
            {
                try
                {
                    customerInfoBLL.SaveForm(keyValue, relationPCEntity, customerInfoEntity);
                    return Success("操作成功。");
                }
                catch (Exception e)
                {
                    return Error(e.Message);
                }
            }
            else
            {
                return Error("当前房间已存在未到期住户。");
            }
        }
        #endregion

        #region 入住单

        /// <summary>
        /// 获取入住单状态树
        /// </summary>
        /// <returns></returns>
        public ActionResult GetStateCountTreeList()
        {
            var data = livebll.GetStateCountTreeList().ToJson().ToJObject();
            List<TreeStatusEntity> lst = new List<TreeStatusEntity>();
            lst.Add(new TreeStatusEntity("0", "所有入住单", "All", Convert.ToInt32(data["All"])));
            lst.Add(new TreeStatusEntity("All", "待入住", "S1", Convert.ToInt32(data["S1"])));
            lst.Add(new TreeStatusEntity("All", "已入住", "S2", Convert.ToInt32(data["S2"])));
            lst.Add(new TreeStatusEntity("All", "到期未退住", "S3", Convert.ToInt32(data["S3"])));
            lst.Add(new TreeStatusEntity("All", "退住中", "S4", Convert.ToInt32(data["S4"])));
            lst.Add(new TreeStatusEntity("All", "已退住", "S5", Convert.ToInt32(data["S5"])));
            lst.Add(new TreeStatusEntity("S1", "未提交", "S11", Convert.ToInt32(data["S11"])));
            lst.Add(new TreeStatusEntity("S1", "审核中", "S12", Convert.ToInt32(data["S12"])));
            lst.Add(new TreeStatusEntity("S1", "待确定", "S13", Convert.ToInt32(data["S13"])));
            lst.Add(new TreeStatusEntity("S2", "10天内退住", "S21", Convert.ToInt32(data["S13"])));
            List<TreeEntity> treeList = new List<TreeEntity>();
            foreach (TreeStatusEntity item in lst)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = lst.Count(t => t.PValue == item.Value) == 0 ? false : true;
                tree.id = item.Value;
                tree.text = item.Text + "(" + item.Count + ")";
                tree.value = item.Value;
                if (item.PValue == "0") tree.isexpand = true;
                else tree.isexpand = false;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.parentId = item.PValue;
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }
        /// <summary>
        /// 分页获取入住单集合
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="queryJson">筛选条件（OrganizeId、State、EndTime、Code、PStructId）</param>
        /// <returns></returns>
        public ActionResult GetLiveInBillPageList(Pagination pagination, string queryJson)
        {
            var queryParam = queryJson.ToJObject();
            if (!queryParam["PStructId"].IsEmpty())
            {
                queryParam["PStructId"] = pstructCache.GetSonStructId(queryParam["PStructId"].ToString());
            }
            if (!queryParam["OrganizeId"].IsEmpty())
            {
                queryParam["OrganizeId"] = organizeCache.GetSonOrganizeId(queryParam["OrganizeId"].ToString());
            }
            var Json = queryParam.ToString();
            var data = livebll.GetLiveInBillPageList(pagination, Json);
            var watch = CommonHelper.TimerStart();
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }

        /// <summary>
        /// 获取入住单详情
        /// </summary>
        /// <param name="keyValue">key</param>
        /// <returns></returns>
        public ActionResult GetLiveInBillInfo(string keyValue)
        {
            var data = livebll.GetLiveInBillInfo(keyValue);
            return Content(data);

        }

        /// <summary>
        /// 获取入住单据房间集合列表
        /// </summary>
        /// <param name="keyValue">单据Id</param>
        /// <returns></returns>
        public ActionResult GetRoomlist(string keyValue)
        {
            var data = livebll.GetLiveInBillDetailList(keyValue);
            List<PStructEntity> lst = new List<PStructEntity>();
            var treeList = new List<TreeEntity>();
            foreach (var item in data)
            {
                PStructEntity entity = new PStructBLL().GetEntity(item.PStructId);
                if (!entity.IsEmpty())
                {
                    TreeEntity tree = new TreeEntity();
                    bool hasChildren = false;
                    tree.id = entity.Id;
                    tree.text = entity.Name;
                    tree.value = entity.Id;
                    tree.title = entity.Name;
                    tree.parentId = "0";
                    tree.isexpand = true;
                    tree.complete = true;
                    tree.hasChildren = hasChildren;
                    treeList.Add(tree);
                }
            }
            return Content(treeList.TreeToJson());
        }

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public ActionResult SubmintLiveBill(string keyValue, string queryJson)
        {

            try
            {
                livebll.SubmintLiveBill(keyValue, queryJson);
                return Success("操作成功！");
            }
            catch (Exception)
            {
                return Error("操作失败！");
                throw;
            }
        }
        /// <summary>
        /// 确认入住
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public ActionResult LiveForm(string keyValue)
        {
            try
            {
                livebll.LiveForm(keyValue);
                return Success("操作成功！");
            }
            catch (Exception)
            {
                return Error("操作失败！");
                throw;
            }
        }
        public ActionResult AuditLiveBill(string keyValue, int Result, string AuditMemo, string RoomDetailList, string RoomMeterList)
        {
            List<RoomDetailEntity> lst1 = RoomDetailList.ToObject<List<RoomDetailEntity>>();
            List<EnergyMeterInfoEntity> lst2 = RoomMeterList.ToObject<List<EnergyMeterInfoEntity>>();
            AuditRecordEntity auditentity = new AuditRecordEntity();
            auditentity.AuditMemo = AuditMemo;
            auditentity.AuditState = Result;
            try
            {
                //装表
                // livebll.InstallTable(keyValue, lst1, lst2);
                //审核
                livebll.AuditLiveBill(keyValue, auditentity);
                return Success("操作成功！");
            }
            catch (Exception e)
            {
                if (e.Message == "没有审核权限！")
                {
                    return Error("没有审核权限！");
                }
                if (e.Message == "数据存在空值，请检查必填字段！")
                {
                    return Error("未配置审核级别！");
                }
                return Error("操作失败！" + e.Message);
                throw;
            }
        }
        /// <summary>
        /// 卸载表
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public ActionResult DelTable(string keyValue, string MeterId)
        {

            try
            {
                livebll.DelTable(keyValue, MeterId);
                return Success("卸载表成功");
            }
            catch (Exception)
            {
                return Error("卸载表失败");
                throw;
            }
        }

        /// <summary>
        /// 新增入住单
        /// </summary>
        /// <param name="Type">1-已存在客户  2-新增客户 </param>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        public ActionResult SaveLiveForm(string queryJson)
        {
            int Type = 0;
            var queryParam = queryJson.ToJObject();
            if (queryParam["CustomerId"].IsEmpty()) Type = 2;
            try
            {
                livebll.SaveLiveForm(queryJson);
                if (Type == 1)
                {
                    return Success("保存成功!");
                }
                else
                {
                    return Success("保存成功，请尽快完善客户资料!");
                }

            }
            catch (Exception)
            {
                return Error("操作失败!");

            }
        }
        #endregion
    }
}
